package com.xjh.t.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.DataGridView;
import com.xjh.t.common.ResultObj;
import com.xjh.t.domain.*;
import com.xjh.t.service.IFileExInfoService;
import com.xjh.t.service.IFileInfoService;
import com.xjh.t.service.IGroupAttrInfoService;
import com.xjh.t.service.IUserInfoService;
import com.xjh.t.vo.FileInfoVo;
import com.xjh.t.vo.OrderInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author satela
 * @since 2020-08-14
 */
@RestController
@RequestMapping("/fileInfo")
public class FileInfoController {

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IGroupAttrInfoService attrInfoService;


    @Autowired
    private IFileExInfoService fileExInfoService;

    @RequestMapping("getFileList")
    public DataGridView getFileList(FileInfoVo vo) throws Exception {
        IPage<FileInfo> page = new Page<>(vo.getPage(), vo.getLimit());
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(vo.getFeCollect() != null && vo.getFeCollect() < 2,"fe_collect",vo.getFeCollect());
        if(StringUtils.isNotBlank(vo.getUploadUserAccount()))
        {
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.like("ur_phonenumber",vo.getUploadUserAccount());
            List<UserInfo> userInfos = this.userInfoService.list(userInfoQueryWrapper);
            List<Integer> userids = new ArrayList<>();
            for(UserInfo userInfo:userInfos)
                userids.add(userInfo.getUrId());
            queryWrapper.in(userids.size() > 0,"ur_id",userids);
        }
        // queryWrapper.eq("or_id","18014398509481985");

        if (vo.getStartTime() == null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String datestr = simpleDateFormat.format(new Date());
            vo.setStartTime(sdf.parse(datestr + " 00:00:00"));
            vo.setEndTime(sdf.parse(datestr + " 23:59:59"));

        }
        queryWrapper.ge(vo.getStartTime() != null, "fe_upload_date", vo.getStartTime());
        queryWrapper.le(vo.getEndTime() != null, "fe_upload_date", vo.getEndTime());

        queryWrapper.orderByDesc("fe_upload_date");

        this.fileInfoService.page(page, queryWrapper);

        List<FileInfoVo> fileInfoVos = new ArrayList<>();

        List<UserInfo> userInfos = this.userInfoService.list();
        Map<Integer, String> userAccount = userInfos.stream().collect(Collectors.toMap(UserInfo::getUrId, UserInfo::getUrPhonenumber));

        for (FileInfo fileInfo : page.getRecords()) {
            FileInfoVo fileInfoVo = new FileInfoVo();
            BeanUtils.copyProperties(fileInfo, fileInfoVo);
            fileInfoVo.parsePicInfo();

            fileInfoVo.setUploadUserAccount(userAccount.get(fileInfo.getUrId()));


            long passdays = (new Date().getTime() - fileInfo.getFeUploadDate().getTime()) / (60 * 60 * 24 * 1000);
            if (passdays >= 30)
                fileInfoVo.setLeftDeleteDays(0);
            else
                fileInfoVo.setLeftDeleteDays(30 - passdays);
            fileInfoVos.add(fileInfoVo);

        }


        return new DataGridView(page.getTotal(), fileInfoVos);

    }
    @RequestMapping("deleteFile")
    public ResultObj deleteFile(FileInfo fileinfo) throws Exception {


      //  this.fileInfoService.removeById(fid);

        if(fileinfo.getFeCollect() ==  0) {
            deletePic("small-thumbnail-image", fileinfo.getFeId() + ".jpg");

            deletePic("large-thumbnail-image", fileinfo.getFeId() + ".jpg");

            deletePic("original-image", fileinfo.getFeId() + "." + fileinfo.getFeType());
        }


        if(fileinfo.getGpId() == 0)
        {
            if(fileinfo.getFeCollect() == 1)
            {
                fileinfo.setGpId(0);
                this.fileInfoService.updateById(fileinfo);
            }
            else
                this.fileInfoService.removeById(fileinfo.getFeId());

            return ResultObj.DELETE_SUCESS;
        }

        GroupAttrInfo attrInfo = attrInfoService.getById(fileinfo.getGpId());
        if(attrInfo != null)
            attrInfo.setFileTotalSize(attrInfo.getFileTotalSize() - fileinfo.getFeSize());
        this.attrInfoService.updateById(attrInfo);

        QueryWrapper<FileExInfo> fileExInfoWrapper = new QueryWrapper<>();
        fileExInfoWrapper.eq("fe_mask_id",fileinfo.getFeId());

        List<FileExInfo> fileExInfos = this.fileExInfoService.list(fileExInfoWrapper);
        for(FileExInfo fileExInfo:fileExInfos) {

            fileExInfo.setFeMaskId(new Long(0));
            this.fileExInfoService.updateById(fileExInfo);
        }

        QueryWrapper<FileExInfo> fileExInfoWrapper2 = new QueryWrapper<>();
        fileExInfoWrapper.eq("fe_back_id",fileinfo.getFeId());

       fileExInfos = this.fileExInfoService.list(fileExInfoWrapper2);
        for(FileExInfo fileExInfo:fileExInfos) {

            fileExInfo.setFeBackId(new Long(0));
            this.fileExInfoService.updateById(fileExInfo);
        }

        this.fileExInfoService.removeById(fileinfo.getFeId());

        if(fileinfo.getFeCollect() == 1)
        {
            fileinfo.setGpId(0);
            this.fileInfoService.updateById(fileinfo);
        }
        else
            this.fileInfoService.removeById(fileinfo.getFeId());

        return ResultObj.DELETE_SUCESS;

    }

    private void deletePic(String bukect,String filename)
    {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIUMo4FyjJNBnT";
        String accessKeySecret = "ghxnlpzdVYVqnUWdNfJjXGVlU1QKEk";
        String bucketName = bukect;
        String objectName = filename;

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, objectName);

// 关闭OSSClient。
        ossClient.shutdown();
    }

    @RequestMapping("collectFile")
    public ResultObj collectFile(FileInfo fileinfo) throws Exception {

        fileinfo.setFeCollect(1);

        this.fileInfoService.updateById(fileinfo);

        return ResultObj.UPDATE_SUCESS;


    }
    @RequestMapping("cancelcollectFile")
    public ResultObj cancelcollectFile(FileInfo fileinfo) throws Exception {

        fileinfo.setFeCollect(0);

        this.fileInfoService.updateById(fileinfo);

        return ResultObj.UPDATE_SUCESS;


    }
}


